package max.ubitest.pipe.view
{
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.events.MouseEvent;
	
	import max.ubitest.pipe.Config;
	import max.ubitest.pipe.data.CellData;
	import max.ubitest.pipe.data.CellValidation;
	import max.ubitest.pipe.data.ComponentTypes;
	import max.ubitest.pipe.events.PipeEvent;
	import max.ubitest.pipe.locators.CellLocator;
	import max.ubitest.pipe.locators.ComponentsLocator;
	
	import org.robotlegs.mvcs.Mediator;
	
	public class CellRendererMediator extends Mediator
	{
		[Inject]
		public var view:CellRenderer;
		[Inject]
		public var cellLocator:CellLocator;
		[Inject]
		public var compLocator:ComponentsLocator;
		
		public function CellRendererMediator()
		{
			super();
		}
		
		override public function onRegister():void{
			eventMap.mapListener(view, MouseEvent.CLICK, onClick);
			eventMap.mapListener(view, MouseEvent.ROLL_OVER, onRollOver);
			eventMap.mapListener(view, MouseEvent.ROLL_OUT, onRollOut);
			eventMap.mapListener(view.data as IEventDispatcher, "validChange", onValidChange);
			eventMap.mapListener(view.data as IEventDispatcher, "componentDataChange", onComponentChange);
		}
		
		private function onRollOver(e:MouseEvent):void{
			if(compLocator.selectedComponent){
				view.alpha = .5;
			}
		}
		
		private function onRollOut(e:MouseEvent):void{
			if(compLocator.selectedComponent){
				view.alpha = 1;
			}
		}
		
		private function onValidChange(e:Event):void{
			if(view.data.valid == CellValidation.VALIDE){
				view.bg.color = 0x1dc04f;
			}else if(view.data.valid == CellValidation.INVALID){
				view.bg.color = 0xde0000;
			}else{
				view.bg.color = 0xE2E2E2;
			}
			setAroundCellsAs(view.data.valid);
		}
		
		private function setAroundCellsAs(valid:String):void{
			if(view.data.componentData.type == ComponentTypes.RESERVOIR){
				var v:Vector.<CellData> = cellLocator.getCellsAround(view.data as CellData);
				for each(var cd:CellData in v){
					cd.valid = valid;
				}
			}
		}
		
		private function onComponentChange(e:Event):void{
			if(view.data.componentData == null){
				view.bg.color = 0xe2e2e2;
			}
		}
		
		private function onClick(e:MouseEvent):void{
			var evt:PipeEvent = new PipeEvent(PipeEvent.CELL_SELECTED, view.data);
			dispatch(evt);
			
			view.alpha = 1;
		}
	}
}